<template>
	<view class="content">
		<nx-reader
			:getChapterContentApi="getChapterContent"
			@initCompleted="initCompleted"
			@pageChange="handlePageChange"
		></nx-reader>
	</view>
</template>

<script>
	
	import {getBookList,getChapterList,getChapterContent} from "@/common/http.api.js"
	export default {
		data() {
			return {
				chapterList:[],
				bookId:""
			};
		},
		onLoad(option) {
			this.bookId = option.bookId;
		},
		methods: {
			// 组件初始化完成
			initCompleted({ setChapterList }) {
				uni.showLoading({
					title: '加载中...'
				});
				
				getChapterList({fictionId: this.bookId,custom: { auth: true }}).then((res) => {
					this.chapterList = res.rows;
					// 阅读历史数据
					// 当前章节index，page-change事件中获取并记录的chapterIndex
					console.log(this.readRecords);
					let readRecords = this.readRecords ? this.readRecords :{chapterIndex:0,topPIndexForChapter:0};
					const chapterIndex =  readRecords[`bookChapterIndex-${this.bookId}`] || 0;
					// 当前章节要展示的段落index，page-change事件中获取并记录的topPIndexForChapter
					const topPIndexForChapter = readRecords[`bookTopPIndexForChapter-${this.bookId}`] || 0;
					setChapterList(this.chapterList, chapterIndex,topPIndexForChapter);
					uni.hideLoading();
				}).catch(() =>{
				})
			},
			/**
			 * 获取章节内容
			 * @param {Object} chapterInfo
			 * @returns 章节内容字符串，可以是html代码，支持async
			 */ 
			getChapterContent(chapterInfo) {
				return new Promise((resolve, reject) => {
					uni.showLoading();
					// 模拟网络加载
					getChapterContent({id: chapterInfo.id,custom: { auth: true }}).then((res) => {
						resolve(res.content || '');
						uni.setNavigationBarTitle({
							title:res.chapterTitle
						})
						uni.hideLoading();
					}).catch(() =>{
					})
				})
			},
			/**
			 * 处理页面切换事件
			 * @param {Object} info
			 */
			handlePageChange(info) {
				const { chapterIndex, topPIndexForChapter } = info;
				// 用于记录阅读历史，之后再initCompleted事件中的setChapterList方法中传递记录的chapterIndex，topPIndexForChapter
				// this.$u.vuex('userInfo', {readRecords:'lz'})
				if(!this.readRecords || Object.keys(this.readRecords).length == 0){
					this.readRecords = {};
				}
				this.readRecords[`bookChapterIndex-${this.bookId}`] = chapterIndex;
				this.readRecords[`bookTopPIndexForChapter-${this.bookId}`] = topPIndexForChapter;
				this.$u.vuex('readRecords', this.readRecords)
			}
		}
	}
</script>

<style>
page {
	width: 100%;
	height: 100%;
}
.content {
	width: 100%;
	height: 100%;
}
</style>
